package com.blacktry.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;

import java.time.Duration;

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // String类型key序列器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // String类型Value序列器
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // Hash类型key序列器
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // Hash类型Value序列器
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        return redisTemplate;
    }


//    @Bean
////////////    自定义基于Redius注解的模板工具RediusThymleaf   实体类可以不实现序列化接口
//    public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//        //分别创建String和josn格式序列化对象，对缓存数据key和value进行转换
//        RedisSerializer<String> serializer = new StringRedisSerializer();
//        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
//        //解决查询缓存转化异常
//        ObjectMapper om=new ObjectMapper();
//        om.setVisibility(PropertyAccessor.ALL,JsonAutoDetect.Visibility.ANY);
//        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//        jackson2JsonRedisSerializer.setObjectMapper(om);
//        //定制缓存数据序列化方式及时效
//        RedisCacheConfiguration config=RedisCacheConfiguration.defaultCacheConfig()
//                .entryTtl(Duration.ofDays(1)).
//                serializeKeysWith(RedisSerializationContext.SerializationPair.
//                        fromSerializer(serializer)).
//                serializeValuesWith(RedisSerializationContext.SerializationPair.
//                        fromSerializer(jackson2JsonRedisSerializer)).disableCachingNullValues();
//        RedisCacheManager cacheManager=RedisCacheManager.builder(redisConnectionFactory)
//                .cacheDefaults(config).build();
//        return cacheManager;
//    }
}
